package com.anydata.android.widget.weatherclock;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

import com.anydata.android.weatherforecast.weather.WeatherCurrentCondition;
import com.anydata.android.weatherforecast.weather.WeatherForecastCondition;
import com.anydata.android.weatherforecast.weather.WeatherSet;
import com.anydata.android.weatherforecast.weather.WeatherUtils;
import com.anydata.android.weatherforecast.weather.shell.WeatherPreference;
import com.anydata.android.weatherforecast.weather.shell.WeeklyForecast;
import com.anydata.android.weatherforecast.weather.webservice.ForecastUtils;
import com.anydata.android.R;


public class WeatherForecastAppWidget extends AppWidgetProvider {
	
	private final static String TAG = "WeatherForecastAppWidget";
	private final static String WEATHER_CONFIG = "android.appwidget.action.APPWIDGET_WEA_CONFIGURE";
	private final static String CLOCK_CONFIG = "android.appwidget.action.APPWIDGET_CLOCK_CONFIGURE";
	
	public static final int tickTime = 5000;
	public static final int delayTime = 0;
	public static final String TODAY = "Today";
	public static final String DAY = "day";
	public static final String ICON = "icon";
	public static final String LOW = "low";
	public static final String HIGH = "high";
	public static final String TEMPERATURE = "temperature";
	public static final String WEATHER_CONDITION = "weather_condition";

	public static List fiveDaysForecast = new ArrayList();
	
    class RunUpdateService extends TimerTask 
    {
    	public Context context = null;    	
    	
    	public void run() 
    	{
    		WeatherForecastAppWidget.this.fixServices(context);
   			//context.startService(new Intent(context, ClockService.class));
    	}
    }

    static RunUpdateService m_serviceTask = null;
	static Timer m_serviceTimer = null;
	
	public void fixServices(Context context)
	{
		if( m_serviceTask == null )
		{
			m_serviceTask = new RunUpdateService();
	 		m_serviceTask.context = context;
		}
		
		if( m_serviceTimer == null )
		{
			m_serviceTimer = new Timer();
			m_serviceTimer.schedule(m_serviceTask, delayTime, tickTime);
		}
	}
	
	public void stopClockService(Context context)
	{
		m_serviceTask.cancel();
		m_serviceTimer.cancel();
		m_serviceTask = null;
		m_serviceTimer = null;
	}
	
	/**
     * {@inheritDoc}
     */
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    	fixServices(context);
    	if (appWidgetIds == null) {
            appWidgetIds = appWidgetManager.getAppWidgetIds(
                    new ComponentName(context, WeatherForecastAppWidget.class));
        }
    	
    	RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.main); 
        AppWidgetManager gm = AppWidgetManager.getInstance(context);
        
        //add the click action for the weather setting activity.
        Intent wsIntent = new Intent(context, WeeklyForecast.class);
        //wsIntent.setAction(WEATHER_CONFIG);
//        WeatherSetting.requestUpdate(appWidgetIds[0]);
//        wsIntent.addCategory(Intent.CATEGORY_LAUNCHER).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[0]);
		PendingIntent wsPi = PendingIntent.getActivity(context, 0, wsIntent,0);
		views.setOnClickPendingIntent(R.id.WeatherAnim, wsPi);
		
		//add the click action for the weather preference activity.
		Intent prefIntent = new Intent(context, WeatherPreference.class);
		PendingIntent prefPi = PendingIntent.getActivity(context, 0, prefIntent, 0);
		views.setOnClickPendingIntent(R.id.location, prefPi);

		
		/*
         * This populates the default values from the preferences XML file. See
         * {@link DefaultValues} for more details.
         */
        PreferenceManager.setDefaultValues(context, R.xml.default_values, false);
		//add the click action for the clock setting activity.
//        Intent clockIntent = new Intent(context, ClockSetting.class);
//        clockIntent.setAction(CLOCK_CONFIG);
//        Bundle clockBundle = new Bundle();
//        clockBundle.putInt(AppWidgetManager.EXTRA_APPWIDGET_ID,appWidgetIds[0]);
//        clockIntent.putExtras(clockBundle);
//        //++ClockSetting.requestUpdate(appWidgetIds[0]);
//        //++clockIntent.addCategory(Intent.CATEGORY_LAUNCHER).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[0]);
        
//		PendingIntent clockPi = PendingIntent.getActivity(context, 0, clockIntent,0);
//		views.setOnClickPendingIntent(R.id.AnalogClock, clockPi);
//		views.setOnClickPendingIntent(R.id.FlipClock, clockPi);
		
		
		
		//Set the analog or digital Clock in main page.
		final SharedPreferences config = context.getSharedPreferences(ConstData.PREF_FILE_NAME, 0);
		String analogOrDigital = config.getString(ConstData.PREFS_CLOCK_MODE_Key, ConstData.ANALOG_CLOCK);
		
		Log.d(TAG, "clock is " + analogOrDigital);
		
		UpdateService.setClockModel(analogOrDigital);
		
		gm.updateAppWidget(appWidgetIds, views);
    	
    	// Request update for these widgets and launch updater service
        UpdateService.requestUpdate(appWidgetIds);
    	
    	Intent widgetUpdate = new Intent();
        //widgetUpdate.setAction(UpdateService.ACTION_UPDATE_ALL);
        widgetUpdate.setClass(context, UpdateService.class);
        
        context.startService(widgetUpdate);
    }
    
    public static RemoteViews updateAppWidget(Context context,WeatherSet ws) {   
    	RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.main); 
    	
    	final SharedPreferences config = context.getSharedPreferences(ConstData.PREF_FILE_NAME, 0);
    	String city_name = config.getString(ConstData.PREFS_CITY_FIELD_Key, ConstData.PREFS_CITY_KEY_DEFAULT);
        Log.d(TAG, "Location is " + city_name);
        
        String temperature_fmt = config.getString(ConstData.PREFS_TEMPTUR_FMT_FIELD_Key, ConstData.PREFS_TEMPTUR_FMT_DEFAULT);
        Log.d(TAG, "Temp fmt is " + temperature_fmt);
        
    	if (null != ws){
    		
    		if(fiveDaysForecast == null)
    			fiveDaysForecast = new ArrayList();
    		
    		if(fiveDaysForecast.size() >= 1)
    			fiveDaysForecast.clear();
    		
    		WeatherCurrentCondition curWeather = ws.getWeatherCurrentCondition();
 			views.setTextViewText(R.id.conditions, curWeather.getCondition());
 			views.setTextViewText(R.id.location, city_name);
 			
 			String temperature = null;
 			
 			if(temperature_fmt.equals(ConstData.PREFS_TEMPTUR_FMT_DEFAULT)){
 				temperature = curWeather.getTempCelcius().toString() + "℃";
 			}else{
 				temperature = curWeather.getTempFahrenheit().toString() + "℉";
 			}
 			views.setTextViewText(R.id.temp, temperature);
 			Map today = new HashMap();
 			today.put(DAY, TODAY);
 			today.put(TEMPERATURE, temperature + "          " + curWeather.getCondition());
 			
 			int iconResource = ForecastUtils.getIconForForecast(curWeather.getCondition(), true);
 			today.put(ICON, iconResource);
 			today.put(WEATHER_CONDITION, 
 					curWeather.getWindCondition()
 					+ "  "
 					+ curWeather.getHumidity());
 			 			
// 			fiveDaysForecast.add(today);
 			
 			ArrayList<WeatherForecastCondition> comingDays = ws.getWeatherForecastConditions();
 			String highT = "", lowT = "";
 			
 			WeatherForecastCondition c = null;
 			if(comingDays != null && comingDays.size() >= 1){
 				c = (WeatherForecastCondition)comingDays.get(0);
 				if(temperature_fmt.equals(ConstData.PREFS_TEMPTUR_FMT_DEFAULT)){
 					highT = c.getTempMaxCelsius();
 	 				lowT = c.getTempMinCelsius();
 				}else{
 					highT = WeatherUtils.celsiusToFahrenheit( c.getTempMaxCelsius() );
 					lowT = WeatherUtils.celsiusToFahrenheit( c.getTempMinCelsius() );
 				}
 			}
 			
 	        views.setTextViewText(R.id.high, highT);
 	        views.setTextViewText(R.id.low, lowT);
 	        views.setImageViewResource(R.id.WeatherAnim, iconResource);
 	        
 	        if(comingDays != null && comingDays.size() >= 1){
 	    	   
 	    	   c = (WeatherForecastCondition)comingDays.get(0);
 	    	   
 	    	   StringBuilder nowStr = new StringBuilder(c.getDayofWeek());
 	    	   SimpleDateFormat format = new SimpleDateFormat("MMM dd");
 	    	   Date curretn_time = new Date();
 	    	   nowStr.append(", ").append(format.format(curretn_time));
 	    	   views.setTextViewText(R.id.date, nowStr.toString());   
 	       }
 	       
 	       for(int i=0; i<comingDays.size(); i++){
 	    	  
 	    	  c = (WeatherForecastCondition)comingDays.get(i);
				if(temperature_fmt.equals(ConstData.PREFS_TEMPTUR_FMT_DEFAULT)){
					highT = c.getTempMaxCelsius() + "℃";
	 				lowT = c.getTempMinCelsius() + "℃";
				}else{
					highT = WeatherUtils.celsiusToFahrenheit( c.getTempMaxCelsius() ) + "℉";
					lowT = WeatherUtils.celsiusToFahrenheit( c.getTempMinCelsius() ) + "℉";
				}
 	    	  if(i==0){
 	    		 today.put(LOW, lowT);
 	    		 today.put(HIGH, highT);
  	    		 fiveDaysForecast.add(today);
  	    	  }else{
  	 	    	   Map d1 = new HashMap();
  	 	 	       d1.put(LOW, lowT);
  	 	 	       d1.put(HIGH, highT);
  	 	 	       d1.put(DAY, c.getDayofWeek());
  	 	 	       d1.put(ICON, ForecastUtils.getIconForForecast(c.getCondition(), true));
  	 	 	       d1.put(WEATHER_CONDITION, c.getCondition());
  	 	 	       fiveDaysForecast.add(d1);	    		  
  	    	  }
 	       }
 	    }
    	return views;
    }   
    
    /*
    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();
        if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action))
        {
        	
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
            
            ComponentName comp_name = new ComponentName("com.android.alarmclock", "com.android.alarmclock.AlarmClock");
            Intent AlarmClockIntent = new Intent(Intent.ACTION_MAIN);
            AlarmClockIntent.addCategory(Intent.CATEGORY_LAUNCHER).setComponent(comp_name);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, AlarmClockIntent, 0);
            views.setOnClickPendingIntent(R.id.AnalogClock, pendingIntent);
            views.setOnClickPendingIntent(R.id.WeatherAnim, pendingIntent);
          
//            ComponentName comp_name = new ComponentName("com.zhifull.android.weatherforecast.weather.shell", 
//      		"com.zhifull.android.weatherforecast.weather.shell.ClockSetting");
          
//		        ComponentName comp_name = new ComponentName("com.zhifull.android.weatherforecast.weather.shell", 
//				"com.zhifull.android.weatherforecast.weather.shell.WeatherSetting");
          
          AppWidgetManager.getInstance(context).updateAppWidget(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), views);
          
        }
        
    }
    */
    
    @Override
    public void onDeleted(Context  context, int[] appWidgetIds){
    	
    	Log.i(TAG, "Stopping the UpdateService....");
    	
    	Intent widgetUpdate = new Intent();

        widgetUpdate.setClass(context, UpdateService.class);
    	
    	context.stopService(widgetUpdate);
    	
    	stopClockService(context);
    	
    	Log.i(TAG, "Stopped the UpdateService.");
    	
    }   
}